package com.yoyo.user.service.impl;

import com.yoyo.user.domain.UniqueIdVO;
import com.yoyo.user.domain.UserInfoVO;
import com.yoyo.user.mapper.UniqueIdMapper;
import com.yoyo.user.service.IUniqueIdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class UniqueIdServiceImpl  implements IUniqueIdService {
    private static final Logger log = LoggerFactory.getLogger(UniqueIdServiceImpl.class);
    @Autowired
    private UniqueIdMapper uniqueIdMapper;

    private static final int START_ID = 1000000;

    /**
     * 生成新的unique_id
     * @return 生成的ID
     */
    @Override
    public String generateUniqueId() {
        // 获取当前最大的系统生成ID
        String lastId = uniqueIdMapper.getLastSystemGeneratedId();
        int nextId = lastId != null ? Integer.parseInt(lastId) + 1 : START_ID;
        // 最多尝试1000个连续数字
        for (int i = 0; i < 1000; i++) {
            String candidateId = String.valueOf(nextId + i);
            try {
                // 检查是否是预留ID
                if (uniqueIdMapper.checkSpecialIdExists(candidateId) > 0) {
                    continue;
                }
                // 检查是否已被使用
                if (uniqueIdMapper.checkIdExists(candidateId) > 0) {
                    continue;
                }
                // 保存生成的ID
                UniqueIdVO uniqueId = UniqueIdVO.builder()
                        .usedId(candidateId)
                        .idType(1) // 系统生成
                        .status(1) // 已使用
                        .assignTime(new Date())
                        .build();

                if (uniqueIdMapper.insert(uniqueId) > 0) {
                    return candidateId;
                }
            } catch (Exception e) {
                log.error("生成ID失败: {}", candidateId, e);
            }
        }

        throw new RuntimeException("无法生成可用的unique_id");
    }
}
